package com.nowcoder.community.controller;

import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.service.ElasticsearchService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 韩
 * @version 1.0
 */
@Controller
public class SearchController implements CommunityConstant {

    @Autowired
    private UserService userService;

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private LikeService likeService;

    @RequestMapping(path = "/search", method = RequestMethod.GET)
    public String search(Model model, String keyword, Page page) {
        //搜索帖子
        SearchHits<DiscussPost> search = elasticsearchService.search(keyword, page.getPageNo() - 1, page.getLimit());
        List<Map<String, Object>> discussposts = new ArrayList<>();
        if (search != null) {
            for (SearchHit<DiscussPost> searchHit : search) {
                Map<String, Object> map = new HashMap<>();
                DiscussPost post = searchHit.getContent();
                System.out.println(post.getTitle());
                //帖子
                map.put("post", post);
                //用户
                map.put("user", userService.findUserById(post.getUserId()));
                //点赞数
                map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));

                discussposts.add(map);
            }
        }
        model.addAttribute("discussposts", discussposts);
        model.addAttribute("keyword", keyword);

        page.setPath("/search?keyword=" + keyword);
        page.setRows(search == null ? 0 : search.getSearchHits().size());

        return "/site/search";

    }
}
